import { httpGet } from './http';

// NOTE: The exact structure of UserSession and SystemInfo should match the API response.
// These are placeholder interfaces.
interface UserSession {
  id: number;
  username: string;
  email: string;
  avatar: string;
}

interface SystemInfo {
  title: string;
  version: string;
  chat_config: object;
  is_login?: boolean;
  notice_key?: string;
  notice?: string;
}

// 客户端ID，用于标识当前浏览器会话
let clientId = '';

// 获取客户端ID
export const getClientId = (): string => {
  if (typeof window === 'undefined') {
    return '';
  }
  if (!clientId) {
    // 从本地存储获取或生成新的客户端ID
    clientId = generateUUID();
    localStorage.setItem('client_id', clientId);
  }
  return clientId;
};

// 生成UUID
const generateUUID = (): string => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
};

// 用户会话信息
let userSession: UserSession | null = null;

// 检查用户会话
export const checkSession = async (): Promise<UserSession> => {
  if (typeof window === 'undefined') {
    return Promise.reject(new Error('Cannot check session on the server.'));
  }
  // 如果已经有会话信息，直接返回
  if (userSession) {
    return userSession;
  }
  
  try {
    // 从服务器获取会话信息
    const res = await httpGet<UserSession>('/api/user/info');
    userSession = res.data;
    return userSession;
  } catch (error) {
    // 会话无效或过期
    clearSession();
    return Promise.reject(error);
  }
};

// 清除会话
export const clearSession = (): void => {
  userSession = null;
  if (typeof window !== 'undefined') {
    localStorage.removeItem('token');
  }
};

// 设置会话
export const setSession = (user: UserSession, token: string): void => {
  if (typeof window === 'undefined') {
    return;
  }
  userSession = user;
  localStorage.setItem('token', token);
};

// 系统信息缓存
let systemInfo: SystemInfo | null = null;

// 获取系统信息
export const getSystemInfo = async (): Promise<{ data: SystemInfo }> => {
  // 如果已经有系统信息，直接返回
  if (systemInfo) {
    return Promise.resolve({ data: systemInfo });
  }
  
  try {
    // 从服务器获取系统信息
    const res = await httpGet<SystemInfo>('/api/config/system');
    systemInfo = res.data;
    return { data: systemInfo };
  } catch (error) {
    return Promise.reject(error);
  }
};

// 更新系统信息
export const updateSystemInfo = (info: SystemInfo): void => {
  systemInfo = info;
};

// 清除系统信息缓存
export const clearSystemInfoCache = (): void => {
  systemInfo = null;
}; 